package cn.jingyinghui.service.impl;

import com.volcengine.ark.runtime.model.embeddings.EmbeddingRequest;
import com.volcengine.ark.runtime.model.embeddings.EmbeddingResult;
import com.volcengine.ark.runtime.service.ArkService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmbeddingService {

    private final ArkService arkService;
    private final String modelName;

    public EmbeddingService(
            @Value("${ark.api-key}") String apiKey,
            @Value("${yiyi.daoubao.embedding.model.name}") String modelName) {
        this.modelName = modelName;
        this.arkService = ArkService.builder()
                .apiKey(apiKey)
                .build();
    }

    public List<Double> generateEmbedding(String text) {
        try {
            // 构建请求
            EmbeddingRequest request = EmbeddingRequest.builder()
                    .model(modelName)
                    .input(List.of(text))
                    .build();

            // 调用豆包API
            EmbeddingResult result = arkService.createEmbeddings(request);

            // 检查结果
            if (result.getData() == null || result.getData().isEmpty()) {
                throw new RuntimeException("豆包API返回空向量");
            }

            // 返回向量
            return result.getData().get(0).getEmbedding();
        } catch (Exception e) {
            throw new RuntimeException("豆包向量生成失败: " + e.getMessage(), e);
        }
    }
}